package com.project.service.sys;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.project.common.UserPwd;
import com.project.common.Constants;
import com.project.common.Page;
import com.project.service.BaseService;
import com.project.common.ConfigBean;
import com.project.dao.sys.RoleDao;
import com.project.dao.sys.UserDao;
import com.project.entity.sys.Permissions;
import com.project.entity.sys.Role;
import com.project.entity.sys.User;
import com.project.service.sys.SysLogService;
import com.project.util.CurrentSessionUtil;
import com.project.util.EncryptString;

/**
 * 用户service
 * @author
 *
 */
@Transactional
@Service
public class UserService extends BaseService<User> {

	@Autowired
	private UserDao userDao;
	
	@Autowired
	private RoleDao roleDao;
	
	@Autowired
	private EncryptString encryptString;
	
	@Autowired
	private ConfigBean configBean;
	
	@Autowired
	private SysLogService sysLogService;

	/**
	 * 删除
	 */
	public void delete(User user){
		userDao.delete(user);
//		User newUser = userDao.getById(user.getId());
//		newUser.setIsDelete(Constants.STATUS_NO);
//		
//		userDao.update(newUser);
		
		/*日志*/
		sysLogService.save("delete", "user", user.getId(), "用户管理-删除用户", "删除用户", "用户"+user.getUserCode()+"已经删除");
	}
	
	/**
	 * 新增用户
	 * @param user
	 */
	public void save(User user,String roleIds,String rightsValueId)throws Exception{
		user.setPassword(encryptString.MD5Encrypt(user.getPassword().trim()));//密码加密
		user.setStatus(Constants.STATUS_OPEN);//默认开启
		user.setCreateUser(CurrentSessionUtil.getCurrentUser().getUserCode());//新建人
		user.setCreateTime(new Date());//新建时间
		user.setUpdateUser(CurrentSessionUtil.getCurrentUser().getUserCode());
		user.setUpdateTime(new Date());
		user.setUserCode(user.getUserCode().trim());
		
		if(StringUtils.isNotEmpty(roleIds)){//如果需要给用户添加角色，则需要绑定该角色
			List<Role> roles = new ArrayList<Role>();
			String [] ids = roleIds.split(",");
			for(String id:ids){
				Role role = roleDao.getById(Long.parseLong(id));
				roles.add(role);
			}
			
			user.setRoles(roles);
		}
		
		userDao.saveOrUpdate(user);
		
		/*日志*/
		sysLogService.save("add", "user", user.getId(), "用户管理-新增用户", "新建用户", "新增用户"+user.getUserCode());
	}
	
	/**
	 * 修改用户
	 * @param user
	 * @param roleIds
	 */
	public void update(User user,String roleIds,String rightsValueId){
		user.setUpdateUser(CurrentSessionUtil.getCurrentUser().getUserCode());//修改人
		user.setUpdateTime(new Date());
	
		List<Role> roles = new ArrayList<Role>();
		if(StringUtils.isNotEmpty(roleIds)){
			String [] ids = roleIds.split(",");
			for(String id:ids){
				Role role = roleDao.getById(Long.parseLong(id));
				roles.add(role);
			}
		}
		user.setRoles(roles);
		
		userDao.saveOrUpdate(user);
		
		/*日志*/
		sysLogService.save("update", "user", user.getId(), "用户管理-修改用户", "修改用户", "用户"+user.getUserCode()+"已修改");
	}
	
	
	/**
	 * 根据userName获取User对象
	 * @param userName
	 * @return
	 */
	public User getByUsername(String userName){
		return userDao.getByUsername(userName);
	}
	
	/**
	 * 分页查询系统用户
	 * @param page
	 * @return
	 */
	public Page<User> queryPage(Page<User> page){
		return userDao.queryPage(page);
	}
	
	/**
	 * 查询已启用的角色
	 * @return
	 */
	public List<Role> queryRolesByStatus(){
		return roleDao.queryRolesByStatus(Constants.STATUS_OPEN);
	}
	
	/**
	 * 启用禁用
	 * @param user
	 * @param status
	 */
	public void doEd(User user, String status){
		user.setStatus(status);
		user.setUpdateUser(CurrentSessionUtil.getCurrentUser().getUserCode());
		user.setUpdateTime(new Date());
		
		String str = "";
		if(Constants.STATUS_CLOSE.equals(status)){
			str = "禁用";
		}else if(Constants.STATUS_OPEN.equals(status)){
			str = "启用";
		}
		
		userDao.update(user);
		
		/*日志*/
		sysLogService.save("E_D", "user", user.getId(), "用户管理-"+str+"用户", str+"用户", "用户"+user.getUserCode()+"被"+str);
	}
	
	/**
	 * 重置密码
	 * @param ids
	 */
	public String resetPwd(String ids){
		String pwd =  encryptString.MD5Encrypt(configBean.getSystemPwd());
		
		if(StringUtils.isNotEmpty(ids)){
			String[] idArray = ids.split(",");
			
			for(String id:idArray){
				User user = userDao.getById(Long.parseLong(id));
				
				user.setPassword(pwd);
				
				userDao.update(user);
				
				/*日志*/
				sysLogService.save("reset", "user", user.getId(), "用户管理-重置用户密码", "重置用户", "用户"+user.getUserCode()+"的密码被重置");
			}
		}
		return configBean.getSystemPwd();
		
	}
	
	/**
	 * 修改密码
	 * @param ids
	 */
	public String updatePwd(UserPwd userPwd){
		User user = userDao.getById(CurrentSessionUtil.getCurrentUser().getId());
    	String oldPassWord=user.getPassword();//用户原密码
    	String oldNewPassword = encryptString.MD5Encrypt(userPwd.getOldPassword());//输入的原密码
    	if(oldNewPassword.equals(oldPassWord)){
    		String passWord =  encryptString.MD5Encrypt(userPwd.getPassword());//输入的新密码
    		user.setPassword(passWord);
			userDao.update(user);
			/*日志*/
			sysLogService.save("update", "user", user.getId(), "用户管理-修改用户密码", "修改用户", "用户"+user.getUserCode()+"的密码被修改");
    		return "true";
    	}else{
    		return "noSame";
    	}
		
	}
	
	/**
	 * 该方法仅限于SecurityRealm类使用
	 * @param userName
	 * @return
	 */
	//@Cacheable(value="usersRole")
	public List<Role> getRolsByUserCode(String userName){
		User user = userDao.getByUsername(userName);
		List<Role> list = new ArrayList<Role>();
	 
		//list.addAll(user.getRoles());
		
		for(Role role:user.getRoles()){
			List<Permissions> permissionsList = new ArrayList<Permissions>();
			
			permissionsList.addAll(role.getPermissions());
			
			list.add(role);
		}
		
		return list;
	}

	
	/**
	 * 查询USERlist集合
	 * @return
	 */
	public List<User> getUserList() {
		List<User> users = userDao.getUserList();
		return users;
	}
	
	
}
